//
//  BaseGaodeMapHandler.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/4/1.
//  Copyright © 2025 aowang. All rights reserved.
//  定位服务工具

import UIKit

/// 高德地图的 Helper
final class GaoDeHelper: NSObject, AMapNaviCompositeManagerDelegate {
    
    static let shared = GaoDeHelper()
    
    private override init() {}
    
    var compositeManager : AMapNaviCompositeManager!

    var initable = false

    func initGaoDe() {
        if initable == false {
            var dyGaodeKey = ""
            let iosA = USERINFO.mapKey.filter{ $0.c_platform == "ios" }
            if iosA.count > 0 {
                
                KSLog("初始化高德x动态--\(iosA.first!.c_map_key.unwrap)")
                
                dyGaodeKey = iosA.first!.c_map_key.unwrap
                AMapServices.shared().apiKey = dyGaodeKey
                
            } else {
                KSLog("初始化高德x固定--\(AppKey.gaoDeKey)")
                
                AMapServices.shared().apiKey = AppKey.gaoDeKey
            }
            
            AMapServices.shared().enableHTTPS = true
            initable = true
        }
    }

}


final class BaseGaodeMapHandler: BaseMapManager {
    
    static let shared = BaseGaodeMapHandler()
    
    var update: (() -> Void)?
    
    private override init() {}
    
    var aMapView:MAMapView?
    
    // reInit 手动告诉控制器重新创建地图 重新进菜单或者换业务都需要重置地图
    // tipOffset 默认居中，配置了偏移可以让提示文字上下移动
    func getMapView(reInit: Bool = false, zoomLevel: Float = 13, showsUserLocation: Bool = false, tipOffset: CGFloat = 0) -> UIView {
        
        if LocationTool.shared.getPermission() {
            
            if aMapView.isNone || reInit {
                // 三部曲才能完全释放，否则高德限制创建10个地图，再创建会变成黑色
                aMapView?.delegate = nil
                aMapView?.removeFromSuperview()
                aMapView = nil

                aMapView = MAMapView()
                aMapView?.delegate = self
                aMapView?.showsUserLocation = showsUserLocation
                aMapView?.zoomLevel = CGFloat(zoomLevel)
            }
            
            if aMapView.isSome {
                return aMapView!
            } else {
                let tipV = UIView()
                addErrorButton(superV: tipV, tipOffset)
                return tipV
            }
            
        } else {
            let tipV = UIView()
            addTipButton(superV: tipV, tipOffset)
            return tipV
        }
    }
    
    
    func setCenterCoordinate(_ coor: CLLocationCoordinate2D) {
        aMapView?.centerCoordinate = coor
    }

    
    func addOverlays(_ overlays: [any MAOverlay]) {
        aMapView?.addOverlays(overlays)
    }
    
    func removeOverlays() {
        if let anOverlays = self.aMapView?.overlays {
            self.aMapView?.removeOverlays(anOverlays)
        }
    }

    func add(_ overlays: MAPolyline) {
        self.aMapView?.add(overlays)
    }
    
    func mapIsScrollEnabled(flag: Bool) {
        self.aMapView?.isScrollEnabled = flag
    }
 
    func removeAnnotations() {
        if let anAnnotations = self.aMapView?.annotations {
            self.aMapView?.removeAnnotations(anAnnotations)
        }
    }

    
    func removeAnnotation(_ annotation: MAAnnotation) {
        self.aMapView?.removeAnnotation(annotation)
    }
    
    func removeAnnotations(_ annotations: [MAAnnotation]) {
        self.aMapView?.removeAnnotations(annotations)
    }

    
    func addAnnotations(_ annotations:[any MAAnnotation]) {
        aMapView?.addAnnotations(annotations)
    }
    
    
    func addAnnotation(_ annotation: MAPointAnnotation) {
        aMapView?.addAnnotation(annotation)
    }
    
    // 地图适应所有的点显示
    func mapViewFitForCoordinates(_ points: [CLLocationCoordinate2D]) {
        var minLat: Double = 90.0
        var maxLat: Double = -90.0
        var minLon: Double = 180.0
        var maxLon: Double = -180.0
        
        for item in points {
            minLat = fmin(minLat, item.latitude)
            maxLat = fmax(maxLat, item.latitude)
            minLon = fmin(minLon, item.longitude)
            maxLon = fmax(maxLon, item.longitude)
        }
        
        let center = CLLocationCoordinate2D(latitude: (minLat + maxLat) * 0.5, longitude: (minLon + maxLon) * 0.5)
        
        var span = MACoordinateSpan()
        span.latitudeDelta = (maxLat - minLat) + 0.01
        span.longitudeDelta = (maxLon - minLon) + 0.01
        var region = MACoordinateRegion()
        region.center = center
        region.span = span
        aMapView?.setRegion(region, animated: true)
    }
    
    
    func mapViewFitPolyLine(_ polyline: MAPolyline!) {
        if polyline.pointCount < 1 {
            return
        }
        
        let pt = polyline.points[0]
        var leftTopX = pt.x
        var leftTopY = pt.y
        var rightBottomX = pt.x
        var rightBottomY = pt.y
        
        for i in 1..<polyline.pointCount {
            let pt = polyline.points[Int(i)]
            leftTopX = pt.x < leftTopX ? pt.x : leftTopX
            leftTopY = pt.y < leftTopY ? pt.y : leftTopY
            rightBottomX = pt.x > rightBottomX ? pt.x : rightBottomX
            rightBottomY = pt.y > rightBottomY ? pt.y : rightBottomY
        }
        
        let rect = MAMapRectMake(leftTopX - (rightBottomX - leftTopX) / 6, leftTopY - (rightBottomY - leftTopY) / 6, (rightBottomX - leftTopX) / 2 * 3, (rightBottomY - leftTopY) / 2 * 3)
        aMapView?.visibleMapRect = rect
    }
}




extension BaseGaodeMapHandler: MAMapViewDelegate {
    //MARK: - MAMapViewDelegate
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        if overlay.isKind(of: MACircle.self) {
            let renderer: MACircleRenderer = MACircleRenderer(overlay: overlay)
            renderer.lineWidth = 0.5
            renderer.strokeColor = UIColor.blue
            renderer.fillColor = UIColor.red.withAlphaComponent(0.4)
            
            return renderer
        }
        if overlay.isKind(of: MAPolyline.self) {
            let renderer: MAPolylineRenderer = MAPolylineRenderer(overlay: overlay)
            renderer.lineWidth = 8.0
            renderer.strokeColor = UIColor.cyan
            
            return renderer
        }
        if overlay.isKind(of: MAPolygon.self) {
            let renderer: MAPolygonRenderer = MAPolygonRenderer(overlay: overlay)
            renderer.lineWidth = 8.0
            renderer.strokeColor = UIColor.green
            renderer.fillColor = UIColor.yellow.withAlphaComponent(0.4)
            return renderer
        }
        
        return nil
        
    }
    
    func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
        if updatingLocation {
            update?()
        }
    }
}
